# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor

label = f"dwd_center_scan_lack_detail_{int(time())}"
timeout = timedelta(minutes=10).seconds
doris_jms_dwd__dwd_center_scan_lack_detail = RichSqlSensor(
    task_id='doris_jms_dwd__dwd_center_scan_lack_detail',
    email=['shenjiaming@jtexpress.com','yl_bigdata@yl-scm.com'],
    pool='broker_load_pool',
    conn_id='new_doris',
    pre_sql=f"""
             TRUNCATE TABLE jms_dwd.dwd_center_scan_lack_detail PARTITION (p{{{{ execution_date | cst_ds_nodash }}}});
             LOAD LABEL jms_dwd.{label} (
                 DATA INFILE("hdfs://{{{{var.value.hadoop_namespace}}}}/dw/hive/jms_dm.db/external/dm_cn_center_scan_lack_detail_dt/dt={{{{ execution_date | cst_ds }}}}/*") 
                 INTO TABLE dwd_center_scan_lack_detail FORMAT AS 'PARQUET'
                 (billcode,terminal_dispatch_code,scan_code,scan_name,agent_code,agent_name,mage_region_code,mage_region_name,arrival_cnt,arrival_time,arrival_packagecode,arrival_pack_create_time,arrival_pack_start_code,arrival_pack_start_name,arrival_pack_end_code,arrival_pack_end_name,arrival_transfercode,arrival_shipment_name,arrival_scanusercode,arrival_scanuser,send_cnt,send_time,send_packagecode,send_pack_start_code,send_pack_start_name,send_scanusercode,send_scanuser,lst_scan_code,lst_scan_name,nxt_scan_code,nxt_scan_name,send_lack_packagecode,send_lack_pack_start_code,send_lack_pack_start_name,order_source_code,order_source_name)
                 SET (dt = DATE('{{{{ execution_date | cst_ds }}}}'))
              )
             WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
             PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dwd WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dwd WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    # execution_timeout=max(datetime.now().replace(hour=8, minute=20, second=0) - datetime.now(), timedelta(seconds=1)),
)


